/*
 * @Author: DUST
 * @Date: 2023-05-29 17:18:15
 * @LastEditors: DUST
 * @LastEditTime: 2023-06-07 10:35:28
 * @FilePath: \koa-node-ts\app\controller\TagsController.ts
 * @Description: 
 * undefined
 */

import { Context } from "koa";
import TagsService from "../service/TagsService";
import responese from "../../utils/responese";
import validate from "../../utils/validator";
import TagsValidator, { tagItem } from "../validator/TagsValidator";


class TagsController {
  /**
   * @description: 查询标签列表
   * @param {Context} ctx：请求体
   */  
  async getTagsList(ctx: Context) {
    const data = await TagsService.getTagList();
    responese.success(ctx, JSON.stringify(data) !== "{}" ? data : []);
  }

  async addTag(ctx: Context) {
    const { data, msg } = await validate<tagItem>(ctx, TagsValidator.addTagRules);

    if(msg !== null) return responese.errorResponese(ctx, msg);
    const [ rows, created ] = await TagsService.addTag(data);
    console.log(rows, created);
    if(!created) return responese.errorResponese(ctx, "该标签已存在");
    if(rows?.id > 0) return responese.success(ctx, null, "新增成功");
    responese.errorResponese(ctx, "新增失败");
  }

  async editTag(ctx: Context){
    const { data: { name, sortNum, id}, msg } = await validate<tagItem & {id: number }>(ctx, TagsValidator.editTagRules);
    if(msg !== null) return responese.errorResponese(ctx, msg);
    if(isNaN(id)) return responese.errorResponese(ctx, "参数id类型错误");
    if(isNaN(sortNum)) return responese.errorResponese(ctx, "参数sortNum类型错误");
    const row = await TagsService.editTag({ name, sortNum: Number(sortNum) }, Number(id));
    console.log("编辑：", row);
    responese.success(ctx, null, "编辑成功");
  }

  async deleteTag(ctx: Context) {
    const params = ctx.params;
    if(isNaN(params.id)) return responese.errorResponese(ctx, "参数id类型错误");

    const data = await TagsService.deleteTag(Number(params.id));
    console.log("删除：", data);
    responese.success(ctx, null, "删除成功");
  }
}

export default new TagsController;